const app = getApp();

Page({
  data: {
    userInfo: null,
    form: {
      username: '',
      phone: '',
      avatar: ''
    },
    loading: false
  },

  onLoad() {
    this.loadUserInfo();
  },

  async loadUserInfo() {
    try {
      const res = await app.request({
        url: '/member/profile/',
        method: 'GET'
      });

      if (res.code === 200) {
        const userInfo = res.data;
        this.setData({
          userInfo,
          form: {
            username: userInfo.username,
            phone: userInfo.phone,
            avatar: userInfo.avatar || '/assets/images/default-avatar.png'
          }
        });
      }
    } catch (error) {
      console.error('获取用户信息失败：', error);
      if (error.statusCode === 401) {
        wx.redirectTo({
          url: '/pages/login/login'
        });
      } else {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    }
  },

  // 输入框事件处理
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`form.${field}`]: e.detail.value
    });
  },

  // 选择头像
  async chooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({
      'form.avatar': avatarUrl
    });
  },

  // 验证表单
  validateForm() {
    const { username, phone } = this.data.form;
    
    if (!username.trim()) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      });
      return false;
    }

    if (!phone.trim()) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return false;
    }

    // 手机号格式验证
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 提交更新
  async handleSubmit() {
    if (this.data.loading) return;
    
    if (!this.validateForm()) return;

    this.setData({ loading: true });

    try {
      const res = await app.request({
        url: '/member/profile/',
        method: 'PUT',
        data: this.data.form
      });

      if (res.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });

        // 更新本地存储的用户信息
        const userInfo = wx.getStorageSync('userInfo') || {};
        wx.setStorageSync('userInfo', {
          ...userInfo,
          ...this.data.form
        });

        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: res.message || '保存失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('更新用户信息失败：', error);
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  }
}); 